<?php

namespace app\logic\user;

use app\common\model\fp\Post;
use app\common\model\fp\PostMedia;
use app\common\model\User;
use app\common\model\UserFollow;
use app\logic\BaseLogic;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;

class FollowLogic extends BaseLogic
{
    /**
     * 获取用户的关注列表
     * @param int $userId 用户id
     * @param int $limit 每页数量
     * @param bool $onlySelectCreator 是否只查询达人
     * @return array
     * @throws ModelNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     */
    public function myFollow(int $userId, int $limit = 10, bool $onlySelectCreator = true): array
    {
        // 获取关注的用户 ID
        $followeeIds = UserFollow::where('follower_id', $userId)->column('followee_id');
        if (empty($followeeIds)) {
            return [];
        }

        // 获取用户基本信息
        $where = [
            ['id', 'in', $followeeIds],
        ];
        if ($onlySelectCreator) {
            $where[] = ['is_creator', '=', 1];
        }

        $result = User::initModel()
            ->where($where)
            ->field('id, nickname, avatar, motto')
            ->paginate($limit);

        $list = $result->items();
        $userIds = $list ? array_column($list, 'id') : [];

        if (!$userIds) {
            return $result->toArray();
        }

        // 分组表名
        $tables = [];
        $tablesMedia = [];
        foreach ($userIds as $uid) {
            $table = Post::getDbTableName($uid);
            $tables[$table][] = $uid; // 表名 => [用户ID列表]

            $tableMedia = PostMedia::getDbTableName($uid);
            $tablesMedia[$tableMedia][] = $uid; // 表名 => [用户ID列表]
        }

        // 查询 Post 数据
        $post = [];
        foreach ($tables as $tableName => $uids) {
            $postTemp = Db::table($tableName)
                ->where('show', '=', 1)
                ->where('status', '=', 1)
                ->where('user_id', 'in', $uids) // 限制当前表的用户 ID
                ->field('id, user_id')
                ->select()
                ->toArray();
            $post = array_merge($post, $postTemp);
        }

        // 按 Post ID 分组
        $postIdsByUser = [];
        foreach ($post as $p) {
            $postIdsByUser[$p['user_id']][] = $p['id'];
        }

        // 查询 Media 数据
        $media = [];
        foreach ($tablesMedia as $tableName => $uids) {
            // 获取当前表的 Post ID
            $currentPostIds = [];
            foreach ($uids as $uid) {
                if (isset($postIdsByUser[$uid])) {
                    $currentPostIds = array_merge($currentPostIds, $postIdsByUser[$uid]);
                }
            }

            if (empty($currentPostIds)) {
                continue;
            }

            // 查询媒体数据
            $mediaTemp = Db::table($tableName)
                ->where('post_id', 'in', $currentPostIds)
                ->field('post_id, media_type, media_url')
                ->select()
                ->toArray();

            foreach ($mediaTemp as $item) {
                $media[$item['post_id']]['post_id'] = $item['post_id'];
                $media[$item['post_id']]['media_type'] = $item['media_type'];
                $media[$item['post_id']]['media_url'][] = $item['media_url'];
            }
        }

        // 统计用户数据
        $userCount = [];
        foreach ($post as $item) {
            $userId = $item['user_id'];
            if (!isset($userCount[$userId])) {
                $userCount[$userId] = [
                    'video_count' => 0,
                    'image_count' => 0,
                ];
            }
            $postId = $item['id'];
            if (isset($media[$postId])) {
                $mediaType = $media[$postId]['media_type'];
                if ($mediaType === 'image') {
                    $userCount[$userId]['image_count'] += count($media[$postId]['media_url']);
                } elseif ($mediaType === 'video') {
                    $userCount[$userId]['video_count'] += 1;
                }
            }
        }

        // 合并统计数据到分页结果
        $result->each(function ($item) use ($userCount) {
            $item['video_count'] = $userCount[$item['id']]['video_count'] ?? 0;
            $item['image_count'] = $userCount[$item['id']]['image_count'] ?? 0;
        });

        return $result->toArray();
    }


    /**
     * 我的粉丝
     * @param int $userId
     * @param int $limit
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function myFans(int $userId, int $limit = 10): array
    {
        // 获取粉丝的 ID
        $fansIds = UserFollow::initModel()->where('followee_id', $userId)->column('follower_id');
        if (empty($fansIds)) {
            return [];
        }

        // 获取用户基本信息
        $result = User::initModel()
            ->where('id', 'in', $fansIds)
            ->field('id, nickname, avatar,motto')
            ->paginate($limit);


        return $result->toArray();
    }


}